<template>
  <view class="label-container">
	  <!-- 标签 -->
    <view class="label-box">
      <view class="label-header">
        <view class="label-title">我的标签</view>
        <view class="label-edit" @click="startEdit">{{isEdit? '完成' :'编辑'}}</view>
      </view>
      <view class="label-content">
        <view  class="label-content-item" v-for="(item,index) in selfLabelList" :key="item._id">
          {{item.name}}
          <uni-icons v-if="isEdit" @click="exditLabel(item,'delete')"
		   class="icon-close" type="clear" size="20" color="red"></uni-icons>
        </view>
        <view v-if="!selfLabelList.length" class="no-data">当前没有数据</view>
      </view>
    </view>
	
	<!-- 推荐标签 -->
    <view class="label-box">
      <view class="label-header">
        <view class="label-title">标签推荐</view>
      </view>
      <view class="label-content">
        <view  @click="exditLabel(item,'edit')" class="label-content-item" v-for="(item,index) in recommendList" :key="index">
          {{item.name}}
        </view>
        <view v-if="!recommendList.length" class="no-data">当前没有数据</view>
      </view>
    </view>
  </view>
</template>

<script>
import {mapState,mapMutations} from 'vuex'
export default {
  data () {
    return {
      isEdit: false, // true开启编辑,变成false为完成提交
	  labelIds: []
    }
  },
  watch:{
	  userInfo:{
		  immediate:true,
		  handler(){
			  this.labelIds = this.userInfo.label_ids
			  if(!this.labelIds) {
				  // 若用户没有编辑过标签
				  this.labelIds = this.labelList.map((item)=>{
					  if(item._id){
						  return item._id
					  }
				  })
			  }
		  }
	  }
  },
  computed:{
	  ...mapState(['labelList']),
	  selfLabelList(){
		  return this.labelList.filter(item => this.labelIds.includes(item._id) && item._id)
	  },
	  recommendList() {
		   return this.labelList.filter(item => !this.labelIds.includes(item._id) && item._id)
	  }
  },
  methods: {
    // 编辑按钮事件
    startEdit () {
	  this.isEdit = !this.isEdit
	  if(!this.isEdit){
		  this._updataLabel()
	  }
    },
	async _updataLabel(){
		const labelIds = this.selfLabelList.map(item => item._id)
		const result = await this.$http.update_label_ids({
			userId:this.userInfo._id,
			label_ids:labelIds
		})
		uni.showToast({
			title:result.msg
		})
		this.updateUserInfo({...this.userInfo,label_ids:labelIds})
	},
	// 编辑当前标签
	async exditLabel(item,type){
		if(this.isEdit){
			if(type === 'edit') {
				await this.labelIds.push(item._id)
			} else if(type === 'delete') {
				this.labelIds = await this.labelIds.filter(id => id !== item._id)
			}
		}
	},
	...mapMutations(['setLabelList'])
  }
}
</script>

<style lang="scss">
@import "./css/labelAdmin.scss";
</style>
